<template>
  <div>
    <form action="/">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        background="#3296fa"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isResultShow = false"
      />
    </form>
    <!-- 模板控制方式1-标准写法 -->
    <!-- <search-result v-if="isResultShow"></search-result>
  <div v-else>
    <search-suggestion v-if="searchText"></search-suggestion>
    <search-history v-else></search-history>
  </div> -->
    <!-- 模板控制方式2-用template优化 -->
    <!-- <search-result v-if="isResultShow"></search-result>
  <template v-else>
    <search-suggestion v-if="searchText"></search-suggestion>
    <search-history v-else></search-history>
  </template> -->
    <!-- 结果 -->
    <search-result
      v-if="isResultShow"
      :search-text="searchText"
    ></search-result>
    <!-- 建议 -->
    <search-suggestion
      v-else-if="searchText"
      :search-text="searchText"
      @search="onSearch"
    ></search-suggestion>
    <!-- 历史 -->
    <search-history
      v-else
      :search-histories="searchHistories"
      @clear-search-histories="searchHistories = []"
      @search="onSearch"
    ></search-history>
  </div>
</template>

<script>
import SearchHistory from '@/views/search/components/search-history'
import SearchResult from '@/views/search/components/search-result'
import SearchSuggestion from '@/views/search/components/search-suggestion'
import { getItem, setItem } from '@/utils/storge'
export default {
  name: 'SearchIndex',
  props: {

  },
  components: { SearchHistory, SearchResult, SearchSuggestion },
  data () {
    return {
      searchText: '', // 输入框输入的内容
      isResultShow: false, // 是否显示搜索结果
      searchHistories: getItem('TOUTIAO_SEARCH_HISTORIES') || []
    }
  },
  created () {},
  mounted () {},
  methods: {
    onSearch (val) {
      this.searchText = val
      // 方式1 splice
      // const index = this.SearchHistories.findIndex(t => t === val)
      // if (index > -1) {
      //   this.SearchHistories.splice(index, 1)
      // }
      // this.searchHistories.unshift(val)
      // 方式2 set
      const set = new Set(this.searchHistories)
      set.delete(val)
      this.searchHistories = [val, ...set]
      this.isResultShow = true
    },
    onCancel () {
      this.$router.back()
    }
  },
  watch: {
    searchHistories (val) {
      setItem('TOUTIAO_SEARCH_HISTORIES', val)
    }
  },
  computed: {}
}
</script>

<style lang="less" scoped>
.van-search__action {
  color: #fff;
}
</style>
